package com.coder306.fastdfs.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

import com.coder306.file.util.FileUtils;
import com.coder306.file.util.IOUtils;

public class FastDFSUtils {

	static TrackerServer trackerServer = null;
	static StorageServer storeStorage = null;
	
	static {
		try {
			ClientGlobal.initByProperties("fastdfs-client.properties");
			TrackerClient client = new TrackerClient(ClientGlobal.g_tracker_group);
			trackerServer = client.getConnection();
			if (trackerServer == null) {
                throw new IllegalStateException("getConnection return null");
            }
			storeStorage = client.getStoreStorage(trackerServer);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MyException e) {
			e.printStackTrace();
		}
	}
	
	public static int delete(String fileId) {
		StorageClient1 client1 = new StorageClient1(trackerServer, storeStorage);
		try {
			return client1.delete_file1(fileId);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MyException e) {
			e.printStackTrace();
		}
		return -1;
	}
	
	public static String upload(byte[] file_buff , String ext) {
		try {
			StorageClient1 client1 = new StorageClient1(trackerServer, storeStorage);
			String upload_appender_file1 = client1.upload_appender_file1(file_buff, ext, null);
			return upload_appender_file1;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MyException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String upload(String filePath) {
		try {
			StorageClient1 client1 = new StorageClient1(trackerServer, storeStorage);
			File file = new File(filePath);
			byte[] file_buff = IOUtils.toByteArray(file);
			String upload_appender_file1 = client1.upload_appender_file1(file_buff, FileUtils.getExtensionName(file.getName()), null);
			return upload_appender_file1;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MyException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
